{% extends "base.html" %}

{% block title %}系统设置 - {{ app_name }}{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>
                <i class="fas fa-cog me-2"></i>
                系统设置
            </h2>
            <div>
                <a href="/admin" class="btn btn-outline-secondary me-2">
                    <i class="fas fa-arrow-left me-2"></i>返回后台
                </a>
                <button type="button" class="btn btn-success" onclick="createBackup()">
                    <i class="fas fa-download me-2"></i>
                    创建备份
                </button>
            </div>
        </div>
        
        <!-- 系统信息卡片 -->
        <div class="row g-4 mb-4">
            <div class="col-md-6">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0">
                            <i class="fas fa-info-circle me-2"></i>
                            系统信息
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row g-3">
                            <div class="col-6">
                                <div class="text-center">
                                    <div class="h3 text-primary mb-1" id="userCount">-</div>
                                    <small class="text-muted">用户总数</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="text-center">
                                    <div class="h3 text-success mb-1" id="passwordCount">-</div>
                                    <small class="text-muted">密码总数</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="text-center">
                                    <div class="h3 text-info mb-1" id="shareCount">-</div>
                                    <small class="text-muted">分享总数</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="text-center">
                                    <div class="h3 text-warning mb-1" id="accessCount">-</div>
                                    <small class="text-muted">访问总数</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0">
                            <i class="fas fa-chart-line me-2"></i>
                            最近访问趋势
                        </h5>
                    </div>
                    <div class="card-body">
                        <canvas id="accessChart" width="400" height="200"></canvas>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 系统配置 -->
        <div class="card border-0 shadow-sm mb-4">
            <div class="card-header bg-light">
                <h5 class="mb-0">
                    <i class="fas fa-sliders-h me-2"></i>
                    系统配置
                </h5>
            </div>
            <div class="card-body">
                <form id="settingsForm">
                    <div class="row g-3">
                        <!-- 基本信息 -->
                        <div class="col-12">
                            <h6 class="text-muted mb-3">基本信息</h6>
                        </div>
                        <div class="col-md-6">
                            <label for="appName" class="form-label">应用名称</label>
                            <input type="text" class="form-control" id="appName" name="app_name" value="{{ current_config.app_name }}" required>
                        </div>
                        <div class="col-md-6">
                            <label for="companyShort" class="form-label">企业简称</label>
                            <input type="text" class="form-control" id="companyShort" name="company_short" value="{{ current_config.company_short }}" required>
                        </div>
                        <div class="col-md-6">
                            <label for="companyFull" class="form-label">企业全称</label>
                            <input type="text" class="form-control" id="companyFull" name="company_full" value="{{ current_config.company_full }}" required>
                        </div>

                    <div class="mt-4">
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i>
                            保存设置
                        </button>
                        <button type="button" class="btn btn-outline-secondary ms-2" onclick="resetForm()">
                            <i class="fas fa-undo me-2"></i>
                            重置
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 数据备份管理 -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-light">
                <h5 class="mb-0">
                    <i class="fas fa-database me-2"></i>
                    数据备份管理
                </h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-8">
                        <div class="table-responsive">
                            <table class="table table-hover" id="backupsTable">
                                <thead>
                                    <tr>
                                        <th>备份文件</th>
                                        <th>创建时间</th>
                                        <th>文件大小</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- 备份列表将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="alert alert-info">
                            <h6><i class="fas fa-info-circle me-2"></i>备份说明</h6>
                            <ul class="mb-0 small">
                                <li>定期备份数据库以防数据丢失</li>
                                <li>备份文件存储在 data/backups 目录</li>
                                <li>建议每周至少备份一次</li>
                                <li>重要操作前请先创建备份</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
$(document).ready(function() {
    loadSystemStats();
    loadBackups();
    
    // 设置表单提交
    $('#settingsForm').on('submit', function(e) {
        e.preventDefault();
        updateSettings();
    });
});

function loadSystemStats() {
    $.ajax({
        url: '/api/system/stats',
        method: 'GET',
        success: function(response) {
            // 更新统计数字
            $('#userCount').text(response.basic_stats.user_count);
            $('#passwordCount').text(response.basic_stats.password_count);
            $('#shareCount').text(response.basic_stats.share_count);
            $('#accessCount').text(response.basic_stats.access_count);
            
            // 绘制访问趋势图
            drawAccessChart(response.recent_accesses);
        },
        error: function() {
            App.Utils.showAlert('加载系统统计失败', 'error');
        }
    });
}

function drawAccessChart(data) {
    const ctx = document.getElementById('accessChart').getContext('2d');
    
    // 准备图表数据
    const labels = data.map(item => item.date);
    const counts = data.map(item => item.count);
    
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: '访问次数',
                data: counts,
                borderColor: 'rgb(75, 192, 192)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                tension: 0.1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

function updateSettings() {
    const formData = new FormData($('#settingsForm')[0]);
    
    // 处理复选框字段 - 确保未选中的复选框也发送false值
    const checkboxFields = [
        { name: 'require_numbers', id: 'requireNumbers' },
        { name: 'require_letters', id: 'requireLetters' },
        { name: 'require_symbols', id: 'requireSymbols' }
    ];
    
    checkboxFields.forEach(function(field) {
        const checkbox = document.getElementById(field.id);
        if (checkbox) {
            // 删除原有值，设置正确的布尔值
            formData.delete(field.name);
            formData.append(field.name, checkbox.checked);
        }
    });
    
    $.ajax({
        url: '/api/settings',
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function(response) {
            App.Utils.showAlert(response.message, 'success');
        },
        error: function(xhr) {
            const error = xhr.responseJSON?.detail || '设置更新失败';
            App.Utils.showAlert(error, 'error');
            console.error('设置更新错误:', xhr.responseText);
        }
    });
}

function resetForm() {
    $('#settingsForm')[0].reset();
    App.Utils.showAlert('表单已重置', 'info');
}

function createBackup() {
    if (!confirm('确定要创建数据备份吗？')) {
        return;
    }
    
    $.ajax({
        url: '/api/system/backup',
        method: 'POST',
        success: function(response) {
            App.Utils.showAlert(response.message, 'success');
            loadBackups(); // 重新加载备份列表
        },
        error: function(xhr) {
            const error = xhr.responseJSON?.detail || '备份创建失败';
            App.Utils.showAlert(error, 'error');
        }
    });
}

function loadBackups() {
    $.ajax({
        url: '/api/system/backups',
        method: 'GET',
        success: function(response) {
            const tbody = $('#backupsTable tbody');
            tbody.empty();
            
            if (response.backups.length === 0) {
                tbody.append(`
                    <tr>
                        <td colspan="4" class="text-center text-muted py-4">
                            <i class="fas fa-database fa-2x mb-2"></i><br>
                            暂无备份文件
                        </td>
                    </tr>
                `);
                return;
            }
            
            response.backups.forEach(function(backup) {
                tbody.append(`
                    <tr>
                        <td>
                            <i class="fas fa-file-archive text-primary me-2"></i>
                            ${backup.filename}
                        </td>
                        <td>${backup.created_at}</td>
                        <td>${backup.size}</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" onclick="downloadBackup('${backup.filename}')" title="下载">
                                <i class="fas fa-download"></i>
                            </button>
                        </td>
                    </tr>
                `);
            });
        },
        error: function() {
            App.Utils.showAlert('加载备份列表失败', 'error');
        }
    });
}

function downloadBackup(filename) {
    window.open(`/api/system/backup/download/${filename}`, '_blank');
}
</script>
{% endblock %}

{% block extra_css %}
<style>
.card {
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.15) !important;
}

#accessChart {
    max-height: 200px;
}
</style>
{% endblock %}